//
//  STSQLManager.swift
//  STVVeibo
//
//  Created by leergou on 16/8/2.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit
// 数据库名称
private let dbName = "ststatus.db"

class STSQLManager: NSObject {
    
    // 全局访问点
    static let sharedTools: STSQLManager = STSQLManager()
    let queue: FMDatabaseQueue
    
    override init() {
        // 路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dbName)
        
        // 打印路径
        print(path)
        
        // 创建或者打开数据库
        queue = FMDatabaseQueue(path: path)
        super.init()
        // 创建表
        creatTable()
    }
    
    //MARK: 创建表的函数
    private func creatTable(){
        // 路径 -> 该文件中存放着 要执行的 sql 语句
        let file = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        // 准备 sql
        let sql = try! String(contentsOfFile: file)
        
        // 建表
        queue.inDatabase { (db) -> Void in
            let result = db.executeStatements(sql)
            if result {
                print("建表成功")
            } else {
                print("建表失败")
            }
        }
    }
    
    // MAKR: 查询数据的公共方法
    func selectRecord(sql: String) -> [[String: AnyObject]]{
        
        // 定义一个可变临时数据
        var tempArray: [[String: AnyObject]] = [[String: AnyObject]]()
        queue.inDatabase { (db) -> Void in
            let resultSet = db.executeQuery(sql, withArgumentsInArray: nil)
            
            print(sql)
            
            print(resultSet)
            
            while resultSet.next() {
                // 定义一个可变字典
                var dict: [String: AnyObject] = [String: AnyObject]()
                // 遍历列数
                for i in 0..<resultSet.columnCount() {
                    let key = resultSet.columnNameForIndex(i)
                    let value = resultSet.objectForColumnIndex(i)
                    dict[key] = value
                }
                // 保存字典
                tempArray.append(dict)
            }
        }
        return tempArray
    }

}
















